package per.zqx.msrw.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import per.zqx.msrw.enums.DBEnum;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * DataSourceConfig,
 *
 * @author Sa, Zhang 2021-12-28 10:05
 */
@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource(){
        return DataSourceBuilder.create().build();
    }
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    public DataSource myRoutingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,
            @Qualifier("slaveDataSource") DataSource slaveDataSource){
        HashMap<Object, Object> targetDataSource = new HashMap<>();
        // key要和上下文内容保持一致，否则无法切换数据源
        targetDataSource.put(DBEnum.MASTER,masterDataSource);
        targetDataSource.put(DBEnum.SLAVE,slaveDataSource);
        MyRoutingDataSource myRoutingDataSource = new MyRoutingDataSource();
        // 默认是读库，读多写少
        myRoutingDataSource.setDefaultTargetDataSource(slaveDataSource);
        myRoutingDataSource.setTargetDataSources(targetDataSource);
        return myRoutingDataSource;
    }
}
